package com.wuyou.mid;

/**
 * @Description 209. 长度最小的子数组
 * @Author 无忧
 * @Date 2023/4/3 9:55
 */
public class MinSubArrayLen {


    public static void main(String[] args) {
        int target = 15;
        int[] nums = {1,2,3,4,5};


        System.out.println(sol_2(target, nums));

    }


    public static int sol_2(int target, int[] nums){
        int ans = 0;
        int l = 0, r = l, sum = 0;
        while (l < nums.length && r < nums.length) {
            sum += nums[r++];
            while (sum >= target) {
                if (ans == 0) {
                    ans = r - l;
                }else {
                    ans = Math.min(ans, r - l);
                }
                sum -= nums[l++];
            }
        }
        return ans;
    }

    // 超时
    public static int sol_1(int target, int[] nums){
        int ans = 0;
        int l = 0;
        while (l < nums.length) {
            int temp = nums[l], r = l + 1;
            while (r < nums.length && temp < target) {
                temp += nums[r++];
            }
            if (temp >= target) {
                if (ans == 0) {
                    ans = r - l;
                }else {
                    ans = Math.min(ans, r - l);
                }
            }
            l++;
        }
        return ans;
    }
}
